package com.bruce.starts.demo.commonerror.cachedesign;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author luotuan
 * @Description
 * @create 2021-05-13 21:03
 **/
@Slf4j
@RestController
@RequestMapping("cacheconcurrent")
public class CacheConcurrentController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    private AtomicInteger atomicInteger = new AtomicInteger();
    @PostConstruct
    public void init(){
        stringRedisTemplate.opsForValue().set("hostTest",getFromDb(),5, TimeUnit.SECONDS);
        log.info("cahce init finished");
    }
    //@Scheduled(fixedRate = 1000)
    private void metrics(){
        log.info("DB QPS {}",atomicInteger.getAndSet(0));
    }
    @GetMapping("getdata")
    public String getData(){
        String data = stringRedisTemplate.opsForValue().get("hostTest");
        if(StringUtils.isEmpty(data)){
            RLock rLock = redissonClient.getLock("locker");
            if(rLock.tryLock()){
                try {
                    data = stringRedisTemplate.opsForValue().get("hostTest");
                    if(StringUtils.isEmpty(data)){
                        data = getFromDb();
                        stringRedisTemplate.opsForValue().set("hostTest",data,5,TimeUnit.SECONDS);
                    }
                }finally {
                    rLock.unlock();
                }
            }
        }
        return data;
    }

    private String getFromDb(){
        atomicInteger.incrementAndGet();
        return "testData";
    }
}
